<template>
  <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body @close="resetForm">
    <span style='font-size: 17px;'>基本信息1</span>
    <el-form ref="form" :model="form" label-width="120px" style='margin-top: 20px;'>
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户姓名" prop="nickname" :verify="verifyName">
            <el-input v-model="form.nickname" placeholder="请输入用户姓名" @input="changeInput"
              :disabled="title == '查看用户' ? true : false" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户组织类型" prop="orgTypeName" verify>
            <!-- <el-select v-model="form.sex" disabled >
                <el-option key="内部" label="内部" value="内部"/>
              </el-select> -->
            <el-input v-model="form.orgTypeName" disabled placeholder="内部" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户账号" prop="username" verify>
            <el-input v-model="form.username" :disabled="title == '编辑用户' ? false : true" placeholder="根据用户姓名自动生成" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户状态" prop="status" v-if="title != '编辑用户'">
            <el-select v-model="form.status" disabled placeholder="请选择">
              <el-option label="在职" value="0" />
              <el-option label="离职" value="1" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户编码" prop="userCode" v-if="title != '新增用户'">
            <el-input v-model="form.userCode" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="证件类型" prop="cardTypeName">
            <el-input v-model="form.cardTypeName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="证件号码" prop="cardNum" :rules="idRule">
            <el-input v-model="form.cardNum" placeholder="请输入"
              :disabled="title == '查看用户' ? true : (form.realnameState == 1 ? true : false)" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="用户手机号" prop="mobile" :verify="verifyPhone" >
            <el-input v-model="form.mobile" placeholder="请输入" :disabled="title == '查看用户' ? true : false" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="所属组织" prop="dept.name" verify>
            <el-input v-model="form.dept.name" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开通平台" prop="openPlatform" verify>
            <el-checkbox-group v-model="form.openPlatform">
              <el-checkbox :disabled="title == '查看用户' ? true : false" label="业务平台"></el-checkbox>
              <el-checkbox :disabled="title == '查看用户' ? true : false" label="管理平台"></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="title != '新增用户'">
        <el-col :span="12">
          <el-form-item label="创建时间" prop="createTime" verify>
            <div class="border" style="background-color: #F5F7FA;">
              <span style="margin-left: 12px;"> {{ parseTime(this.form.createTime) }}</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户状态" prop="status">
            <el-select v-model="form.status" disabled placeholder="请选择">
              <el-option label="在职" value="0" />
              <el-option label="离职" value="1" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="角色设置" verify>
            <div class="border">
              <el-tag v-for="tag in form.role.enableRoleNames" :key="tag" :closable="title == '查看用户' ? false : true"
                @close="handleRemove('1', tag)">{{ tag }}</el-tag>
              <el-tag v-for="tag in form.role.disableRoleNames" :key="tag" closable type="info"
                @close="handleRemove('3', tag)">{{ tag }}</el-tag>
              <div class="add">
                <el-button plain size="mini" icon="el-icon-plus" :disabled="title == '查看用户'"
                  @click="handleinit('1')">添加</el-button>
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="用户组设置" verify>
            <div class="border">
              <el-tag v-for="tag in form.userGroupNames" :key="tag" :closable="title == '查看用户' ? false : true"
                @close="handleRemoveGroup(tag)">{{ tag }}</el-tag>
              <div class="add">
                <el-button plain size="mini" icon="el-icon-plus" :disabled="title == '查看用户'"
                  @click="handleinitGroup('1')">添加</el-button>
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="兼职组织" prop="dept">
            <div class="border">
              <el-tag v-for="tag in form.dept.additionalDeptNames" :key="tag" closable @close="handleRemove('2', tag)">{{
                tag }}</el-tag>
              <div class="add">
                <el-button plain size="mini" icon="el-icon-plus" :disabled="title == '查看用户'"
                  @click="handleinit('2')">添加</el-button>
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <template v-if="title != '新增用户'">
        <div style='font-size: 17px;padding: 10px 0;'>三方系统账号</div>
        <el-row>
          <el-col :span="12">
            <el-form-item label="实名状态">
              <el-select v-model="form.thirdAccountRealNameStatus" disabled placeholder="请选择">
                <el-option label="未实名" :value="0" />
                <el-option label="已实名" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="5G随意签SaaS账号">
              <el-input v-model="form.thirdAccount5G" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </template> -->
      <groupDialog ref="groupUser" @callbackGroup="callbackGroup"></groupDialog>
      <roleDialog ref="roleUser" @callback="callback"></roleDialog>
      <userDialog ref="userDialog" @emitplayer="emitplayer"></userDialog>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import Treeselect from "@riophae/vue-treeselect";
import userDialog from "@/components/common/userDialog/index.vue";
import roleDialog from "@/components/common/roleDialog/index.vue";
import groupDialog from "@/components/common/groupDialog/index.vue";
import { generateUserName } from "../../../api/system/role";
import { addUser, getUser, updateUser } from "../../../api/system/user";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { forEach } from "min-dash";

let defaultForm = {
  cardTypeName: "身份证",
  cardType: 1,
  status: "0",
  orgTypeName: "内部",
  nickname: '',
  username: '',
  openPlatform: [],
  orgType: 0,
  dept: {
    additionalDeptIds: [],
    additionalDeptNames: [],
    name: '',
    id: ''
  },
  role: {
    disableRoleIds: [],
    disableRoleNames: [],
    enableRoleIds: [4],
    enableRoleNames: ['普通用户'],
  }
}
export default {
  components: { Treeselect, userDialog, roleDialog, groupDialog },
  data() {
    let changeId = (rule, value, callback) => {
      if (!value) { //所以当没有值的时候，我们直接callback，让他不校验直接执行下一步
        return callback()
      } else {
        if (this.$util.verifyIdCard(value)) {  //验证通过也下一步
          return callback();
        } else {
          callback(new Error("请输入正确的证件号码")); //验证不通过下一步只是抛出个错误
        }
      }
    }
    let changePhone = (rule, value, callback) => {
      if (!value) { //所以当没有值的时候，我们直接callback，让他不校验直接执行下一步
        return callback()
      } else {
        if (this.$util.verifyMobile(value)) {  //验证通过也下一步
          return callback();
        } else {
          callback(new Error("请输入正确格式的手机号")); //验证不通过下一步只是抛出个错误
        }
      }
    }
    return {
      title: "",
      form: JSON.parse(JSON.stringify(defaultForm)),
      open: false,
      idRule: [{ required: false, validator: changeId, trigger: 'blur' }],
      idRulePhone: [{ required: false, validator: changePhone, trigger: 'blur' }],
    };
  },
  methods: {
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getRole(id).then((response) => {
        // this.form = response.data;
        this.open = true;
        this.title = "编辑用户";
      });
    },
    handleadd(type, item) {
      if (type == "0") {
        //新增用户
        this.open = true;
        this.title = "新增用户";
        this.form.dept.id = item.id;
        this.form.dept.name = item.name;
      } else if (type == "2") {
        //编辑用户git puh
        this.title = "编辑用户";
        getUser(item).then((response) => {
          console.log(response);
          // this.form = Object.assign(this.form, response.data);
          this.form = { ...this.form, ...response.data }
          this.form.status = this.form.status.toString();
          this.form.openPlatform = this.form.openPlatform.split(",");
          this.open = true;
          console.log(this.form, "this.form---");
        });
      } else {
        //查看用户
        this.title = "查看用户";
        getUser(item).then((response) => {
          this.form = Object.assign(this.form, response.data);
          this.form.status = this.form.status.toString();
          this.form.openPlatform = this.form.openPlatform.split(",");
          this.open = true;
          console.log(this.form, "this.form---");
        });
      }
    },

    // 删除角色，兼职人员
    handleRemove(type, val) {
      if (type == "1") {//角色
        let index = this.form.role.enableRoleNames.indexOf(val)
        this.form.role.enableRoleNames.splice(index, 1);
        this.form.role.enableRoleIds.splice(index, 1);
        console.log(index, 'index--', this.form.role)
      } else if (type == "2") {
        let index = this.form.dept.additionalDeptNames.indexOf(val)
        this.form.dept.additionalDeptIds.splice(index, 1);
        this.form.dept.additionalDeptNames.splice(index, 1);
        console.log(index, 'index-1-', this.form.dept)
      } else {
        let index = this.form.role.disableRoleNames.indexOf(val)
        this.form.role.disableRoleIds.splice(index, 1);
        this.form.role.disableRoleNames.splice(index, 1);
        console.log(index, 'index-1-', this.form.dept)
      }
    },
    handleRemoveGroup(val) {
      let index = this.form.userGroupNames.indexOf(val)
      this.form.userGroupNames.splice(index, 1);
      this.form.userGroupIds.splice(index, 1);
      console.log(index, 'index--', this.form.userGroupNames)
    },
    //兼职组织回调
    emitplayer(Ids = []) {
      let additionalDeptIds = Ids.map((item) => {
        return item.id;
      });
      let additionalDeptNames = Ids.map((item) => {
        return item.name;
      });
      this.$set(this.form.dept, "additionalDeptIds", additionalDeptIds);
      this.$set(this.form.dept, "additionalDeptNames", additionalDeptNames);
    },
    handleinitGroup() {
      console.log(this.form, '--this.form.userGroupIds')
      this.$refs.groupUser.init("", this.form.userGroupIds || [], this.form.userGroupNames || [], this.form.dept.id);
    },
    handleinit(type) {
      if (type == "1") {//角色
        console.log(this.form, '--this.form.role')
        debugger
        this.$refs.roleUser.init("", this.form.role.enableRoleIds || [], this.form.role.enableRoleNames || [], this.form.dept.id);
      } else {
        let additional = []
        if (this.form.dept.additionalDeptIds) {
          this.form.dept.additionalDeptIds.forEach((item, index) => {
            let temp = {
              id: item,
              name: this.form.dept.additionalDeptNames[index]
            }
            additional.push(temp)
          });
        }
        this.$refs.userDialog.init("", additional || [], this.form.dept.id);
      }
    },
    callback(Ids = []) {
      let roleIds = Ids.map((item) => {
        return item.id;
      });
      let roleNames = Ids.map((item) => {
        return item.name;
      });
      this.$set(this.form.role, "enableRoleIds", roleIds);
      this.$set(this.form.role, "enableRoleNames", roleNames);
    },
    callbackGroup(Ids = []) {
      let groupIds = Ids.map((item) => {
        return item.id;
      });
      let groupNames = Ids.map((item) => {
        return item.name;
      });
      this.$set(this.form, "userGroupIds", groupIds);
      this.$set(this.form, "userGroupNames", groupNames);
    },
    changeInput(string) {
      console.log(string, "string----");
      this.$nextTick(() => {
        generateUserName(string).then((response) => {
          console.log(response.data, "000----");
          this.$set(this.form, "username", response.data);
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (this.title == "查看用户") {
        this.open = false;
      } else {
        this.$refs.form.validate(valid => {
          if (valid) {
            if (this.form.role.disableRoleIds.length > 0) {
              this.$modal.msgError("请将禁用角色删除后才能保存!");
              return
            }
            let form = JSON.parse(JSON.stringify(this.form));
            form.additionalDeptIds = form.dept.additionalDeptIds
            form.deptId = form.dept.id;
            form.roleIds = this.form.role.enableRoleIds
            form.openPlatform = form.openPlatform.toString();
            if (form.openPlatform == [] || form.nickname == '') {
              this.$modal.msgError("还有必填项未选择!");
              return
            }
            // if ((form.email == null || form.email == '') && (form.mobile == null || form.mobile == '')) {
            //   this.$modal.msgError("邮箱和手机号不能同时不填！");
            //   return
            // }
            form.source = 1;
            form.status = 0
            delete form.dept;
            delete form.role;
            delete form.orgTypeName;
            delete form.cardTypeName;
            console.log(form, "arrny---", this.form);
            if (this.title == "新增用户") {
              form.password = "123456";
              console.log('jiek', form)
              addUser(form).then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.$emit("getList");
              });
            } else if (this.title == "编辑用户") {
              console.log(form, "this.form---");
              form.orgType = 0,
                updateUser(form).then((response) => {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.$emit("getList");
                });
            }
          }
        })

      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      // this.resetForm();
    },
    /** 重置按钮操作 */
    resetForm() {
      this.form = JSON.parse(JSON.stringify(defaultForm))
      // this.form = []
      // this.form = {
      //   cardTypeName: "身份证",
      //   orgTypeName: "内部",
      //   openPlatform: [],
      //   dept: {},
      // };
      // this.resetForm("form"); // 被封装好的 element 方法 可用 入参传ref
      // this.handleQuery();
    },
    verifyName(rule, val, callback) {
      if (val) {
        if (val.length < 2 || val.length > 50) callback(Error('用户姓名支持输入2-50个字'));
        let re = /^[\u4E00-\u9FA5A-Za-z]+$/;
        if (!re.test(val)) callback(Error('支持中文、英文（区分大小写）'));
        else callback();
      } else {
        callback();
      }
    },
    verifyPhone(rule, val, callback) {
      if (val) {
        if(this.$util.verifyMobile(val)){
          callback();
        }else{
          callback(Error('请输入正确格式的手机号'))
        }
      } else {
        callback();
      }
    },
  },
};
</script>
<style scoped>
.border {
  width: 100%;
  /* height: 30px; */
  height: auto;
  min-height: 30px;
  border-radius: 5px;
  border: 1px solid #dfe4ed;
}

::v-deep .border-bottom {
  border-bottom: 1px solid #f4f6fa;

  .el-button--small {
    padding: 0px 10px;
  }
}

.border-left {
  border-left: 1px solid #f4f6fa;
}

.border-right {
  border-right: 1px solid #f4f6fa;
}

.add {
  display: inline-block;
}
</style>